package com.gitee.wsl.ext.array.bytes


fun ByteArray.toCharArray() = CharArray(size) {
    get(it).toInt().toChar()
}

fun CharArray.toByteArray() = concatToString().encodeToByteArray()


/**
 * Converts a char array to a byte array with given charset and range
 *
 *
 *
 * **Analysis**
 *
 *  * Time Complexity: `O(n)`
 *  * Space Complexity: `O(n)`
 *  * Alters Parameters: `false`
 *
 *
 *
 * @param charArray to get the byte array from
 * @param charset   charset to be used to decode the char array
 * @param offset    to start reading the char array from (must be smaller than length and gt 0)
 * @param length    from offset (must be between 0 and charArray.length())
 * @return byte array of encoded chars
 */
//fun charToByteArray(charArray: CharArray, charset: Charset, offset: Int, length: Int): ByteArray {
//    require(!(offset < 0 || offset > charArray.size)) { "offset must be gt 0 and smaller than array length" }
//    require(!(length < 0 || length > charArray.size)) { "length must be at least 1 and less than array length" }
//    require(offset + length <= charArray.size) { "length + offset must be smaller than array length" }
//
//    if (length == 0) return ByteArray(0)
//
//    var charBuffer: CharBuffer = CharBuffer.wrap(charArray)
//
//    if (offset != 0 || length != charBuffer.remaining()) {
//        charBuffer = charBuffer.subSequence(offset, offset + length)
//    }
//
//    val bb: ByteBuffer = charset.encode(charBuffer)
//    if (bb.capacity() !== bb.limit()) {
//        val bytes = ByteArray(bb.remaining())
//        bb.get(bytes)
//        return bytes
//    }
//    return bb.array()
//}

/**
 * Convert given byte array in given encoding to char array
 *
 *
 *
 * **Analysis**
 *
 *  * Time Complexity: `O(n)`
 *  * Space Complexity: `O(n)`
 *  * Alters Parameters: `false`
 *
 *
 *
 * @param bytes     as data source
 * @param charset   of the byte array
 * @param byteOrder the order of the bytes array
 * @return char array
 */
//fun byteToCharArray(bytes: ByteArray, charset: Charset, byteOrder: ByteOrder): CharArray {
//    try {
//        val charBuffer: CharBuffer = charset.decode(ByteBuffer.wrap(bytes).order(byteOrder))
//        if (charBuffer.capacity() !== charBuffer.limit()) {
//            val compacted = CharArray(charBuffer.remaining())
//            charBuffer.get(compacted)
//            return compacted
//        }
//        return charBuffer.array()
//    } catch (e: CharacterCodingException) {
//        throw IllegalStateException(e)
//    }
//}
